﻿using GsOrganization.Common.Extend;
using GsOrganization.Common.Helper;
using GsOrganization.TcpPacket;
using GsOrganization.TcpPacket.PayLoad;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GsOrganization.TcpServer
{
    /// <summary>
    /// 应用程序启动类
    /// </summary>
    public class TcpStartup
    {
        private Thread th_CheckOfflineTime;

        public TcpStartup(int port)
        {
            LogHelper.Information("Service Init...");
            UpdateToOffline();//分布式这样就部合适了，两台启动有先后，在线
            TcpResourcesManager.TcpServer = new CollectServer(port, LogHelper.GetLogger());
            Initialize();
            th_CheckOfflineTime = new Thread(CheckDeviceOffline);
            th_CheckOfflineTime.IsBackground = true;
            th_CheckOfflineTime.Start();
            StartTcpServer();
        }

        private void UpdateToOffline()
        {
            //var client = this.GetDBClient();
            //client.Updateable<Equpmentinfo>().SetColumns(t => new Equpmentinfo { OnlineState = "0" }).Where(t => t.OnlineState == "1").ExecuteCommand();
            //SysLogger.SvcLogger.Information("Set all device to offline complete");
        }

        private void CheckDeviceOffline()
        {
            while (true)
            {
                //每隔10分钟，执行一次
                Thread.Sleep(10 * 60 * 1000);
                try
                {
                    LogHelper.Information("开始检查设备离线时间");
                    ProcessCheckDeviceOffline();
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex, $"开始检查设备离线时间{ex.Message}");
                }
            }
        }

        public int StartTcpServer()
        {
            int tcpstartresult = TcpResourcesManager.TcpServer.StartServerSocket();
            if (tcpstartresult != 0)
            {
                LogHelper.Error("tcpServer启动失败!");
                return 2;
            }
            LogHelper.Error("tcpServer启动完成...");
            return 0;
        }



        private void ProcessCheckDeviceOffline()
        {
            //var client = this.GetDBClient();
            //List<Equpmentinfo> toDisable = new List<Equpmentinfo>();
            //var DeviceInfos = client.Queryable<Equpmentinfo>().Where(t => t.ActiveState == "激活" && t.OnlineState == "0" && t.EqState == "启用").ToList();

            //foreach (var devinfo in DeviceInfos)
            //{
            //    if (devinfo.LastOfflineTime.HasValue)
            //    {
            //        if (devinfo.ModifyStateTime.HasValue)
            //        {
            //            if (DateTime.Now.Date == devinfo.LastOfflineTime.Value.Date)
            //            {
            //                //当天修改过状态
            //                continue;
            //            }
            //        }
            //        if ((DateTime.Now - devinfo.LastOfflineTime.Value).TotalDays > devinfo.OffLineLockDay)
            //        {
            //            //有下线时间按下线时间算
            //            devinfo.EqState = "锁定";
            //            devinfo.Upremark = $"系统扫描：离线时间已超过最大限制时间[{devinfo.OffLineLockDay}天]";
            //            devinfo.UpdateTime = DateTime.Now;
            //            devinfo.ModifyStateTime = DateTime.Now;
            //            toDisable.Add(devinfo);
            //            Logger.SysLogger.SvcLogger.Information($"设备超过最大离线时长：Id={devinfo.Id},DevSerialNum={devinfo.EqCode},DevCode={devinfo.HardwareCode}");
            //        }
            //    }
            //    else if (devinfo.ActiveTime.HasValue)
            //    {
            //        //没有下线时间按激活时间算
            //        if ((DateTime.Now - devinfo.ActiveTime.Value).TotalDays > devinfo.OffLineLockDay)
            //        {
            //            devinfo.EqState = "锁定";
            //            devinfo.Upremark = $"系统扫描：激活后未使用时间已超过最大限制时间[{devinfo.OffLineLockDay}天]";
            //            devinfo.UpdateTime = DateTime.Now;
            //            devinfo.ModifyStateTime = DateTime.Now;
            //            toDisable.Add(devinfo);
            //            Logger.SysLogger.SvcLogger.Information($"设备激活后未使用超过最大限制：Id={devinfo.Id},DevSerialNum={devinfo.EqCode},DevCode={devinfo.HardwareCode}");
            //        }
            //    }
            //    else
            //    {
            //        //这俩都没有，不处理，按理不应该
            //    }
            //}
            //int cnt = client.Updateable(toDisable).UpdateColumns("EqState", "Upremark", "UpdateTime").ExecuteCommand();
            //Logger.SysLogger.SvcLogger.Information($"检查设备离线时间任务完成，本次禁用{cnt}个设备");
        }

        /// <summary>
        /// 初始化回调函数
        /// </summary>
        private void Initialize()
        {
            LogHelper.Information("Service Init CallBack Funcations...");
            TcpResourcesManager.TcpServer.OnRecvLogin = OnRecvClientLogin;
            TcpResourcesManager.TcpServer.OnClientDisconnect = OnClientDisconnect;
            //TcpResourcesManager.TcpServer.SetAction(MessageCommandId.SendCarAndLatLongDataRsp, TcpCallBackLogic.OnRecvCarAndLatLongData);
            LogHelper.Information("Service Init CallBack Funcations Complete...");
        }

        /// <summary>
        /// 客户端登录
        /// </summary>
        /// <param name="clientSession"></param>
        /// <param name="deviceLoginReq"></param>
        /// <returns></returns>
        public static DeviceLoginResp OnRecvClientLogin(ClientSession clientSession, Header head, DeviceLoginReq deviceLoginReq)
        {

            LogHelper.Information($"OnRecvClientLogin SessionId={clientSession.SessionId},ReqInfo={deviceLoginReq.ToJsonString()}");
            DeviceLoginResp resp = new DeviceLoginResp()
            {
                DeviceState = 0,
                DeviceStateDesc = "正常",
                DeviceValid = 0
            };
            ServerMessagePacket packet;
            //目前仅验证设备时区是否正常
            if (head.GetTimeRemain() > 300)
            {
                clientSession.Dispose();
                resp.DeviceValid = 1;
                resp.DeviceState = 0;
                resp.DeviceStateDesc = "设备时间异常";
                packet = new ServerMessagePacket(MessageCommandId.DeviceLoginRsp, resp.ToJsonString());
                clientSession.SendMessage(packet);
            }
            else
            {
                packet = new ServerMessagePacket(MessageCommandId.DeviceLoginRsp, resp.ToJsonString());
                clientSession.SendMessage(packet);
            }
            return resp;
        }

        public static void OnClientDisconnect(string ClientId, string DBID)
        {
            LogHelper.Information($"OnClientDisconnect {DBID},ClientId={ClientId}");
            if (DBID.IsNullOrEmpty())
                return;
        }
    }
}
